package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory> implements BrowsingHistoryService {

    private final BrowsingHistoryMapper browsingHistoryMapper;

    @Override
    public IPage<HistoryItemVo> pageHistoryItemVo(Page<HistoryItemVo> page) {
        return baseMapper.pageHistoryItemVo(page);
    }

    /*
    保存细节:
        1.只有当用户首次浏览房间信息时才向记录表中插入一条记录
        2.如果同一个用户多次浏览同一个房间详情,不应该保存多条记录，只刷新记录时间
    */
    @Override
    @Async  // 被该注解所标注的方法统一为异步执行 --> springBoot会另外创建一个子线程来单独执行该方法  (有点像Promise中的 async|await)
    public void saveHistory(Long userId, Long roomId) {
        // 测试@Async
        System.out.println("saveHistory(): ===  " + Thread.currentThread().getName());

        // 判断当前用户是否为首次浏览
        BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(new LambdaQueryWrapper<BrowsingHistory>().eq(BrowsingHistory::getUserId, userId).eq(BrowsingHistory::getRoomId, roomId));
        if (browsingHistory != null){
            // 非首次,更新记录时间
            browsingHistory.setBrowseTime(new Date());
            browsingHistoryMapper.updateById(browsingHistory);
        }else {
            // 首次,save
            browsingHistoryMapper.insert(new BrowsingHistory(userId,roomId,new Date()));
        }

    }
}




